package com.tripspins.app.helper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

import com.tripspins.app.FacebookContactsActivity;
import com.tripspins.app.R;
import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.Contact;
import com.facebook.model.GraphUser;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Joao on 10/18/2014.
 */
public class NewAttachmentsHelper {

    private final FileHelper fileHelper;
    private final Activity activity;

    public NewAttachmentsHelper(Activity activity){
        fileHelper = new FileHelper(activity);
        this.activity = activity;
    }

    public Uri takePicture() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri fileUri = fileHelper.saveFile(FILE_TYPE.IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        activity.startActivityForResult(intent, ConstantsHelper.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        return fileUri;
    }
    public Uri recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        Uri fileUri = fileHelper.saveFile(FILE_TYPE.VIDEO);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
        intent.putExtra("FILE_TYPE", FILE_TYPE.VIDEO.getValue());
        // start the image capture Intent
        activity.startActivityForResult(intent, ConstantsHelper.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
        return fileUri;
    }
    public Uri recordAudio() {
        Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        Uri fileUri = fileHelper.saveFile(FILE_TYPE.VIDEO);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
        activity.startActivityForResult(intent, ConstantsHelper.CAPTURE_AUDIO_ACTIVITY_REQUEST_CODE);
        return fileUri;
    }
    public void pickImage(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, ConstantsHelper.PICK_IMAGE_ACTIVITY_REQUEST_CODE);
    }
    public void meetContact() {
        OpenContactsDialog dialog = new OpenContactsDialog();
        dialog.setParameter(this);
        dialog.show(activity.getFragmentManager(), "TAG");
    }

    public ArrayList<Attachment> getFacebookContacts(List<GraphUser> selectedUsers) {
        ArrayList<Attachment> atts = new ArrayList<Attachment>();
        for(GraphUser user : selectedUsers)
        {
            Attachment att = new Attachment();
            att.setFileType(FILE_TYPE.CONTACT.getValue());
            Contact contact = new Contact();
            contact.setContactIdOnSource(user.getId());
            contact.setName(user.getName());
            att.setContact(contact);
            atts.add(att);
        }
        return atts;
    }

    public Attachment getPickedImage(Intent data) {
        if(data.getData() != null){
            Uri selectedImage = data.getData();
            String picturePath;
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.getContentResolver().query(selectedImage, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                picturePath = cursor.getString(column_index);
                Uri newFileUri = fileHelper.saveFile(FILE_TYPE.IMAGE, picturePath);
                Attachment att = new Attachment();
                att.setPath(newFileUri.getPath());
                att.setFileType(FILE_TYPE.IMAGE.getValue());
                try {
                    ThumbnailsHelper.generateThumbnail(new File(att.getPath()), FILE_TYPE.IMAGE, activity);
                } catch (Exception ex) {
                }
                return att;
            }
        }
        return null;
    }

    public static class OpenContactsDialog extends DialogFragment {

        static NewAttachmentsHelper newAttachmentsHelper;

        public static void setParameter(NewAttachmentsHelper n){
            newAttachmentsHelper = n;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.dialog_meet_contact);
            builder.setItems(R.array.dialog_contact_options, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int index) {
                    newAttachmentsHelper.getContact(index);
                }
            });
            return builder.create();
        }
    }
    public void getContact(int index){
        Intent intent;
        switch (index) {
            case 0:
                /*intent = new Intent(Intent.ACTION_INSERT);
                intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
                startActivityForResult(intent, ConstantsHelper.CONTACTS_ACTIVITY_REQUEST_CODE);*/
                break;
            case 1:
                /*intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, ConstantsHelper.CONTACTS_ACTIVITY_REQUEST_CODE);*/
                break;
            case 2:
                /*intent = new Intent();
                intent.setData(ConstantsHelper.FRIEND_PICKER);
                intent.setClass(activity, FacebookContactsActivity.class);
                activity.startActivityForResult(intent, ConstantsHelper.FACEBOOK_CONTACTS_ACTIVITY_REQUEST_CODE);*/
                break;
            default:
                break;
        }
    }
    public Attachment getNewPicture(Uri fileUri){
        Attachment att = new Attachment();
        att.setPath(fileUri.getPath());
        att.setFileType(FILE_TYPE.IMAGE.getValue());
        try{
            ThumbnailsHelper.generateThumbnail(new File(att.getPath()),FILE_TYPE.IMAGE, activity);
        }catch(Exception ex){
            try {
                System.gc();
                ThumbnailsHelper.generateThumbnail(new File(att.getPath()), FILE_TYPE.IMAGE, activity);
            }catch (Exception ex2){}
        }
        return att;
    }
    public Attachment getNewVideo(Uri fileUri) {
        Attachment att = new Attachment();
        att.setPath(fileUri.getPath());
        att.setFileType(FILE_TYPE.VIDEO.getValue());
        try{
            ThumbnailsHelper.generateThumbnail(new File(att.getPath()), FILE_TYPE.VIDEO, activity);
        }catch(Exception ex){}
        return att;
    }
    public Attachment getNewAudio(Intent data) {
        Cursor cursor = activity.getContentResolver().query(data.getData(), null, null, null, null);
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
        String path = cursor.getString(index);
        File tempDir = fileHelper.getAttachmentsTemporaryDirectory();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File tempFile = new File(tempDir.getPath() + "/AUD_" + timeStamp + path.substring(path.lastIndexOf(".")));
        fileHelper.moveFile(path, tempFile.getPath());
        Attachment att = new Attachment();
        att.setPath(tempFile.getPath());
        att.setFileType(FILE_TYPE.AUDIO.getValue());
        return att;

    }
    public Attachment getContact(Intent data) {
        Contact contact = new Contact();
        Uri contactUri = data.getData();
        String id = contactUri.getLastPathSegment();
        Cursor basicInfo = activity.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI
                , null
                , ContactsContract.Contacts.Data._ID + "=?"
                , new String[]{id}
                , null);


        int nameIdx = basicInfo.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        int pictureIdx = basicInfo.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI);
        int phoneNumberIdx = basicInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        int emailIdx = basicInfo.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS);
        basicInfo.moveToFirst();
        if(!basicInfo.isAfterLast()){
            contact.setName(basicInfo.getString(nameIdx));
            contact.setPictureThumbnailPath(basicInfo.getString(pictureIdx));
            contact.setPhoneNumber(basicInfo.getString(phoneNumberIdx));
            contact.setEmail(basicInfo.getString(emailIdx));

            Attachment att = new Attachment();
            if(new File(contact.getPictureThumbnailPath()).exists())
                att.setPath(contact.getPictureThumbnailPath());
            else
                att.setPath("android.resource://com.android.tripsandpins.app/ic_contact_picture");
            att.setContact(contact);
            att.setFileType(FILE_TYPE.CONTACT.getValue());
            return att;
        }
        return null;

    }

}
